package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.api.system.dto.CustomerInfoDTO;
import com.yk.common.core.exception.ServiceException;
import com.yk.system.entity.CustomerInfo;
import com.yk.system.mapper.CustomerInfoMapper;
import com.yk.system.service.CustomerInfoService;
import com.yk.system.vo.CustomerInfoRdStatisticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 客户信息 服务类
 *
 * @author lmx
 * @since 2023-11-10
 */
@Service
@RequiredArgsConstructor
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Override
    public void check(CustomerInfoDTO dto) {
        if (StrUtil.isEmpty(dto.getCompanyName())) {
            throw new ServiceException("公司名不能为空");
        }
        if (Objects.nonNull(dto.getId())) {
            CustomerInfo customerInfo = baseMapper.selectById(dto.getId());
            if (customerInfo.getCompanyName().equals(dto.getCompanyName())) {
                return;
            }
        }

        Long count = baseMapper.selectCount(new LambdaQueryWrapper<CustomerInfo>()
                .eq(CustomerInfo::getCompanyName, dto.getCompanyName()));
        if (count > 0) {
            throw new ServiceException("公司名已存在");
        }
        Long countPhone = baseMapper.selectCount(new LambdaQueryWrapper<CustomerInfo>()
                .eq(CustomerInfo::getPhone, dto.getPhone()));
        if (countPhone > 0) {
            throw new ServiceException("手机号已存在");
        }
    }

    @Override
    public List<CustomerInfoRdStatisticsVO> rdStatistics() {
        return baseMapper.rdStatistics();
    }

    @Override
    public String getCompanyNameByPhone(String phone) {
        if (StrUtil.isEmpty(phone)){
            return null;
        }
        LambdaQueryWrapper<CustomerInfo> lambda = new LambdaQueryWrapper<>();
        lambda.eq(CustomerInfo::getPhone, phone);
        List<CustomerInfo> customerInfos = baseMapper.selectList(lambda);
        if (CollUtil.isNotEmpty(customerInfos)){
            return customerInfos.get(0).getPhone();
        }
        return null;
    }
}